package com.xieyong.mywebsite.exception;

import com.xieyong.mywebsite.model.dto.Result;
import jakarta.validation.ValidationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//全局异常捕获器
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    public Result<Exception> error(Exception e) {
        logger.error("系统异常：", e);
        return Result.error(StringUtils.hasLength(e.getMessage()) ? "系统异常 ：" + e.getMessage() : "系统异常！！");
    }

    @ExceptionHandler(MyCustomizeException.class)
    public Result<MyCustomizeException> customizeError(MyCustomizeException e) {
        logger.error("自定义错误：", e);
        return Result.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(BindException.class)
    public Result<BindException> customizeError(BindException e) {
        logger.error("校验错误：", e);
        return Result.error("校验错误：" + e.getBindingResult().getFieldError().getDefaultMessage());
    }
    @ExceptionHandler(ValidationException.class)
    public Result<ValidationException> customizeError(ValidationException e) {
        logger.error("校验错误：", e);
        return Result.error("校验错误：" + e.getMessage());
    }
}
